/*
* Copyright 2010 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/

package org.bookmarksframework.core
{
	public class Map
	{
		protected var storage:IStorage;
		
		public function initialize(storage:IStorage):void
		{
			this.storage = storage;
		}
		
		public function getActive():XML
		{
			var xml:XML = <map/>;
			activeRecursively(storage.getChildren(), xml);
			return xml;
		}
		
		public function getView():XML
		{
			var xml:XML = <map/>;
			viewRecursively(storage.getChildren(), xml);
			return xml;
		}
		
		protected function activeRecursively(controllers:Vector.<FacileHierarchy>, 
											 xml:XML):void
		{
			var controller:IFragmentController;
			var controllerChildren:Vector.<FacileHierarchy>;
			var child:XML;
			
			for (var i:int = 0; i < controllers.length; ++i)
			{
				controller = controllers[i].value as IFragmentController;
				
				if (controller && controller.fragment.active)
				{
					child = <{controller.fragment.part}/>;
					child.@uid = controller.fragment.uid;
					xml.appendChild(child);
					
					controllerChildren = controllers[i].getChildren();
					
					if (controllerChildren.length)
					{
						arguments.callee.call(null, controllerChildren, child);
					}
				}
			}
		}
		
		protected function viewRecursively(controllers:Vector.<FacileHierarchy>, 
										   xml:XML):void
		{
			var fragment:IFragment;
			var controller:IFragmentController;
			var controllerChildren:Vector.<FacileHierarchy>;
			var child:XML;
			
			for (var i:int = 0; i < controllers.length; ++i)
			{
				controller = controllers[i].value as IFragmentController;
				
				if (controller)
				{
					fragment = controller.fragment;
					child = <Fragment/>;
					if (fragment.id)
						child.@id = fragment.id;
					child.@uid = fragment.uid;
					child.@active = fragment.active;
					child.@enabled = fragment.enabled;
					child.@part = fragment.part;
					child.@value = fragment.value;
					child.@rule = fragment.rule;
					child.@targetField = fragment.targetField;
					child.@target = fragment.target;
					child.@host = fragment.host;
					xml.appendChild(child);
					
					controllerChildren = controllers[i].getChildren();
					
					if (controllerChildren.length)
					{
						arguments.callee.call(null, controllerChildren, child);
					}
				}
			}
		}
	}
}